package com.apestech.formwork.condition;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.SaveTableCallback;
import com.apestech.framework.util.StringFuncUtil;
import com.apestech.framework.xml.condition.modul.Account;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-03-05-14:45
 */
public class ExecAccount extends StringFuncUtil implements SaveTableCallback {

    private Account.Bill bill;
    private Account account;

    public ExecAccount(Account account, Account.Bill bill){
        this.account=account;
        this.bill=bill;
    }

    @Override
    public boolean before(String tabName) throws Exception {
        return true;
    }

    @Override
    public void write(String tabName, JSONObject input, int index, SqlSession session) throws Exception {
        if(account.getBillFromUpdate(tabName)!=null){
            Account.UpdateTable updateTable=account.getBillFromUpdate(tabName).getUpdateTable(tabName);
            String keyValue=input.getString(updateTable.getKeyField());
            if(keyValue==null) return;
            String aTabName=account.getConditon().getTableKey().getTableFromValue(keyValue);
            String sql="UPDATE "+aTabName+" SET ";
            JSONObject param=new JSONObject();
            ArrayList<String> list=account.getUpdateKey();
            int len=list.size();
            for(int i=0; i<len; i++){
                String key=list.get(i);
                Account.Update update=account.getUpdate(key);
                String trigger=update.getTrigger();
                String field=update.getField();
                String result=update.getResult();
                sql=sql+field+"=#{"+field+"} ";
                JSONObject eparam=new JSONObject();
                eparam=account.getConditon().getDimensionCondtionParam(account.getConditon().getTableKey().getDimensionId(), input);
                eparam.put("ID", keyValue);


                /*
                0)根据account定义生成对应单据的表名，并记录对应表编码至account档案下,难点：相关单据表
                0）单据保存时写单据扩展表
                1）查询帐目原始数据，需要将本次更新的字段和时间错全部查出
                2）重新构造参与计算返回值的MAP，代入计算公式，获取对应更新帐目的SQL
                3）执行更新帐目SQL；
                */
                //JSONArray qlist=session.getForJSON().query("SELECT "+aTabName+" WHERE ")

//                eparam.putAll(input);
//                eparam.put(field, )
                param.put(field, doExpression(result, eparam));

            }
        }
    }

    @Override
    public String after(String tabName, JSONObject input) throws Exception {
        return null;
    }
}
